﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Ninject;

namespace ecdl.demo.model.word {
    public interface IDocxLoader {
        /// <summary>
        /// Reads the docx from the given file.
        /// </summary>
        /// <param name="fileName">the relative path to the filename. The path will be appended to the applicatoins IVolumeProvider's path</param>
        /// <exception cref="System.io.FileNotFoundException"></exception>
        /// <exception cref="System.IO.FileFormatException"></exception>
        /// <returns>the docx document</returns>
        WordprocessingDocument ReadDocument(string fileName);
    }

    public class DefaultDocxLoader : IDocxLoader {
        private IVolumeProvider pathProvider;

        [Inject]
        public DefaultDocxLoader(IVolumeProvider pathProvider) {
            this.pathProvider = pathProvider;
        }

        public WordprocessingDocument ReadDocument(string fileName) {
            string fullPath = pathProvider.GetFullPath(fileName);
            try {
                //first make a copy of the file
                string tempFile = Path.GetTempFileName();
                File.Copy(fullPath, tempFile, true);
                return WordprocessingDocument.Open(tempFile, false);
            } catch (FileNotFoundException e) {
                throw e;
            } catch (Exception e) {
                throw new System.IO.FileFormatException(fileName + " ist kein gültiges docx.", e);
            }
        }
    }
}
